package com.aifund.admin.service.impl;

import com.aifund.admin.entity.form.system_msg.AddSystemMsgForm;
import com.aifund.admin.entity.form.system_msg.EditSystemMsgForm;
import com.aifund.admin.entity.form.system_msg.SystemMsgPageForm;
import com.aifund.admin.entity.vo.PageResult;
import com.aifund.admin.service.SystemMsgService;
import com.aifund.common.dao.SystemMsgDao;
import com.aifund.common.entity.SystemMsg;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class SystemMsgServiceImpl implements SystemMsgService {

    @Autowired
    SystemMsgDao systemMsgDao;

    @Override
    public PageResult<SystemMsg> systemMsgList(SystemMsgPageForm form) {
        Specification<SystemMsg> specification = new Specification<SystemMsg>() {
            @Override
            public Predicate toPredicate(Root<SystemMsg> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        Sort sort = Sort.by(Sort.Direction.ASC,"createTime");
        Pageable pageable = PageRequest.of(form.getPageIndex()-1,form.getPageSize(),sort);
        Page<SystemMsg> systemMsgs = systemMsgDao.findAll(specification, pageable);
        PageResult<SystemMsg> pageResult = new PageResult<>();
        return pageResult.success(systemMsgs,form.getPageIndex()-1,form.getPageSize());
    }

    @Override
    public void addSystemMsg(AddSystemMsgForm form) {
        SystemMsg systemMsg = new SystemMsg();
        BeanUtils.copyProperties(form,systemMsg);
        systemMsgDao.save(systemMsg);
    }

    @Override
    public void editSystemMsg(EditSystemMsgForm form) {
        SystemMsg systemMsg = systemMsgDao.getById(form.getId());
        BeanUtils.copyProperties(form,systemMsg);
        systemMsgDao.save(systemMsg);
    }

    @Override
    public void delSystemMsg(Long id) {
        systemMsgDao.deleteById(id);
    }

    @Override
    public SystemMsg getById(Long id) {
        return systemMsgDao.getById(id);
    }


}
